package com.wyh.yuhcloud.filter;



import com.wyh.yuhcloud.util.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

/**
 * @author wyh
 * @version 1.0
 * @date 2021/10/5 15:28
 */

public class TokenAuthFilter extends BasicAuthenticationFilter {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;


    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取用户信息
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request,response);
        //如果信息为空就让其他过滤器处理
        if (authRequest != null) {
            //不为空就添加信息到上下文中
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        //通过
        chain.doFilter(request, response);

    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //根据token获取用户名信息
        String token = request.getHeader("Authorization");
        if (token!=null){
            String userId = tokenManager.getUserIdFromToken(token);
            //从redis获取用户权限
            //List<String> authenticationList = (List<String>) redisTemplate.opsForValue().get(username);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            /*if (authenticationList!=null){
                for (String authentication : authenticationList) {
                    authorities.add(new SimpleGrantedAuthority(authentication));
                }
            }*/
            authorities.add(new SimpleGrantedAuthority(((Integer) Objects.requireNonNull(redisTemplate.opsForValue().get(userId))).toString()));
            return new UsernamePasswordAuthenticationToken(userId,token,authorities);
        }
        else {
            response.sendRedirect("/toLogin");
            return null;
        }
    }
}
